import Food from './Food'
import ScorePanel from './ScorePanel'
import Snake from './Snake'
class GameControl {
  food: Food;
  scorepanel: ScorePanel;
  snake: Snake;
  //创建一个属性用来存蛇的移动方向
  direction: string = '';
  isLive = true;
  legalKeyDown: string[] = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']
  constructor() {
    this.food = new Food()
    this.scorepanel = new ScorePanel()
    this.snake = new Snake()
    this.init()
  }
  init() {
    document.addEventListener('keydown', this.keydownHeader.bind(this))
    this.run()
    this.snake.addBody()
  }
  keydownHeader(event: KeyboardEvent) {
    this.legalKeyDown.some(item => {
      if (item === event.key) {
        this.direction = event.key
        return true
      }
    })
  }
  run() {
    let X = this.snake.X;
    let Y = this.snake.Y;
    switch (this.direction) {
      case "ArrowUp":
        Y -= 10;
        break;
      case "ArrowDown":
        Y += 10
        break
      case "ArrowLeft":
        X -= 10
        break
      case "ArrowRight":
        X += 10
        break
    }

    this.checkEat(X, Y)
    try {
      this.snake.X = X
      this.snake.Y = Y
    } catch(e) {
      alert(e)
      this.isLive = false
    }
    this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorepanel.level - 1) * 30)
  }
  // 是否迟到了食物
  checkEat(X:number,Y:number) {
    if(this.food.X === X && this.food.Y === Y) {
      this.food.change()
      this.snake.addBody()
      this.scorepanel.addScore()
    }
  }
}

export default GameControl